import React, { useEffect, useState } from 'react';
import { getAccountInfo, getAccountTransactions, rechargeAccount, withdrawAccount, transferAccount } from '../service/api';
import { Button, Toast, Dialog, List, Input, Selector, Tabs, TextArea } from 'antd-mobile';
import { useNavigate } from 'react-router-dom';

const banks = [
  { label: '招商银行 - 6225 **** 4322', value: 1 },
  { label: '工商银行 - 6222 **** 8765', value: 2 },
  { label: '建设银行 - 6227 **** 1357', value: 3 },
];

export default function Home() {
  const [account, setAccount] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [rechargeVisible, setRechargeVisible] = useState(false);
  const [withdrawVisible, setWithdrawVisible] = useState(false);
  const [transferVisible, setTransferVisible] = useState(false);
  const [bankId, setBankId] = useState<number | undefined>();
  const [amount, setAmount] = useState<string>('');
  const [remark, setRemark] = useState('');
  const [toAccountNo, setToAccountNo] = useState('');
  const [transactions, setTransactions] = useState<any[]>([]);
  const [tab, setTab] = useState('transactions');
  const navigate = useNavigate();

  useEffect(() => {
    fetchAccount();
    fetchTransactions();
  }, []);

  const fetchAccount = async () => {
    setLoading(true);
    try {
      const res = await getAccountInfo();
      setAccount(res.data.data);
    } finally {
      setLoading(false);
    }
  };

  const fetchTransactions = async () => {
    // 假设userId已存储在localStorage
    const userId = localStorage.getItem('userId') || '';
    const res = await getAccountTransactions({ userId, current: 1, pageSize: 10 });
    setTransactions(res.data.data.records || []);
  };

  const handleRecharge = async () => {
    if (!bankId) {
      Toast.show({ content: '请选择银行卡' });
      return;
    }
    if (!amount || isNaN(Number(amount)) || Number(amount) < 10) {
      Toast.show({ content: '请输入正确的充值金额(≥10元)' });
      return;
    }
    Toast.show({ icon: 'loading', content: '充值处理中...' });
    try {
      await rechargeAccount({ bankId, amount: Number(amount), remark });
      Toast.show({ icon: 'success', content: '充值申请已提交' });
      setRechargeVisible(false);
      setAmount('');
      setRemark('');
      setBankId(undefined);
      fetchAccount();
      fetchTransactions();
    } catch {
      Toast.show({ icon: 'fail', content: '充值失败' });
    }
  };

  const handleWithdraw = async () => {
    if (!bankId) {
      Toast.show({ content: '请选择银行卡' });
      return;
    }
    if (!amount || isNaN(Number(amount)) || Number(amount) < 10) {
      Toast.show({ content: '请输入正确的提现金额(≥10元)' });
      return;
    }
    Toast.show({ icon: 'loading', content: '提现处理中...' });
    try {
      await withdrawAccount({ bankId, amount: Number(amount), remark });
      Toast.show({ icon: 'success', content: '提现申请已提交' });
      setWithdrawVisible(false);
      setAmount('');
      setRemark('');
      setBankId(undefined);
      fetchAccount();
      fetchTransactions();
    } catch {
      Toast.show({ icon: 'fail', content: '提现失败' });
    }
  };

  const handleTransfer = async () => {
    if (!toAccountNo) {
      Toast.show({ content: '请输入对方账户' });
      return;
    }
    if (!amount || isNaN(Number(amount)) || Number(amount) < 1) {
      Toast.show({ content: '请输入正确的转账金额(≥1元)' });
      return;
    }
    Toast.show({ icon: 'loading', content: '转账处理中...' });
    try {
      await transferAccount({ toAccountNo, amount: Number(amount), remark });
      Toast.show({ icon: 'success', content: '转账成功' });
      setTransferVisible(false);
      setAmount('');
      setRemark('');
      setToAccountNo('');
      fetchAccount();
      fetchTransactions();
    } catch {
      Toast.show({ icon: 'fail', content: '转账失败' });
    }
  };

  return (
    <div style={{ padding: 12, background: '#f5f7fa', height: '100vh' }}>
      <div style={{ background: '#fff', borderRadius: 8, padding: 16, marginBottom: 16 }}>
        <div style={{ fontWeight: 600, fontSize: 18, marginBottom: 8 }}>账户总览</div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
          <div>
            <div style={{ color: '#888', fontSize: 13 }}>账户余额</div>
            <div style={{ fontSize: 22, color: '#3f8600', fontWeight: 700 }}>¥{account?.balance?.toFixed(2) || '0.00'}</div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <Button color="primary" size="small" onClick={() => { setRechargeVisible(true); return; }}>充值</Button>
            <Button color="warning" size="small" onClick={() => { setWithdrawVisible(true); return; }}>提现</Button>
            <Button color="default" size="small" onClick={() => { setTransferVisible(true); return; }}>转账</Button>
          </div>
        </div>
        <div style={{ color: '#888', fontSize: 13 }}>可用余额：¥{account ? (account.balance - (account.frozenAmount || 0)).toFixed(2) : '0.00'}</div>
        <div style={{ color: '#faad14', fontSize: 13 }}>冻结金额：¥{account?.frozenAmount?.toFixed(2) || '0.00'}</div>
        <div style={{ color: '#888', fontSize: 12, marginTop: 4 }}>最后更新：{account?.updatedAt || '-'}</div>
        <div style={{ marginTop: 8 }}>
          <Button size="small" onClick={() => { fetchAccount(); return; }}>刷新</Button>
          <Button size="small" style={{ marginLeft: 8 }} onClick={() => { navigate('/user'); return; }}>用户月账单</Button>
        </div>
      </div>
      <Tabs activeKey={tab} onChange={setTab} style={{ background: '#fff', borderRadius: 8 }}>
        <Tabs.Tab title="交易明细" key="transactions">
          <List header="最近交易">
            {transactions.length === 0 && <List.Item>暂无交易记录</List.Item>}
            {transactions.map(item => (
              <List.Item key={item.transactionNo} description={item.remark} onClick={() => navigate(`/transaction/${item.transactionNo}`)}>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <span style={{ color: item.transactionType === 1 ? '#52c41a' : '#f5222d' }}>{item.transactionType === 1 ? '+' : '-'}¥{item.amount.toFixed(2)}</span>
                  <span style={{ fontSize: 12, color: '#888' }}>{item.createdAt}</span>
                </div>
              </List.Item>
            ))}
          </List>
        </Tabs.Tab>
        <Tabs.Tab title="冻结资金" key="frozen">
          <div style={{ padding: 16, color: '#888' }}>暂无冻结资金</div>
        </Tabs.Tab>
      </Tabs>
      <Dialog
        visible={rechargeVisible}
        title="账户充值"
        content={
          <div>
            <Selector
              options={banks}
              value={bankId ? [bankId] : []}
              onChange={val => setBankId(val[0])}
              style={{ marginBottom: 12 }}
            />
            <Input
              placeholder="充值金额(元)"
              type="number"
              value={amount}
              onChange={setAmount}
              style={{ marginBottom: 12 }}
            />
            <TextArea
              placeholder="充值说明(选填)"
              value={remark}
              onChange={setRemark}
              style={{ marginBottom: 12 }}
              rows={2}
            />
            <div style={{ color: '#888', fontSize: 12 }}>
              1. 充值金额将从您绑定的银行卡转入虚拟账户；<br />
              2. 充值一般实时到账，部分银行可能有延迟；<br />
              3. 如遇到问题，请联系客服。
            </div>
          </div>
        }
        onClose={() => setRechargeVisible(false)}
        actions={[
          { key: 'cancel', text: '取消', onClick: () => { return; } },
          { key: 'ok', text: '确认充值', bold: true, onClick: () => { handleRecharge(); return; } },
        ]}
      />
      <Dialog
        visible={withdrawVisible}
        title="账户提现"
        content={
          <div>
            <Selector
              options={banks}
              value={bankId ? [bankId] : []}
              onChange={val => setBankId(val[0])}
              style={{ marginBottom: 12 }}
            />
            <Input
              placeholder="提现金额(元)"
              type="number"
              value={amount}
              onChange={setAmount}
              style={{ marginBottom: 12 }}
            />
            <TextArea
              placeholder="提现说明(选填)"
              value={remark}
              onChange={setRemark}
              style={{ marginBottom: 12 }}
              rows={2}
            />
            <div style={{ color: '#888', fontSize: 12 }}>
              1. 提现金额将转入您选择的银行卡；<br />
              2. 提现一般1-2小时到账，部分银行可能有延迟；<br />
              3. 如遇到问题，请联系客服。
            </div>
          </div>
        }
        onClose={() => setWithdrawVisible(false)}
        actions={[
          { key: 'cancel', text: '取消', onClick: () => { return; } },
          { key: 'ok', text: '确认提现', bold: true, onClick: () => { handleWithdraw(); return; } },
        ]}
      />
      <Dialog
        visible={transferVisible}
        title="账户转账"
        content={
          <div>
            <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
              <Input
                placeholder="对方账户（账号/卡号）"
                value={toAccountNo}
                onChange={setToAccountNo}
                style={{ flex: 1 }}
              />
              <Button size="small" color="primary" onClick={() => navigate('/scan')}>扫码</Button>
            </div>
            <Input
              placeholder="转账金额(元)"
              type="number"
              value={amount}
              onChange={setAmount}
              style={{ marginBottom: 12 }}
            />
            <TextArea
              placeholder="转账说明(选填)"
              value={remark}
              onChange={setRemark}
              style={{ marginBottom: 12 }}
              rows={2}
            />
            <div style={{ color: '#888', fontSize: 12 }}>
              1. 请确认对方账户信息无误，转账提交后不可撤销；<br />
              2. 如遇到问题，请联系客服。
            </div>
          </div>
        }
        onClose={() => setTransferVisible(false)}
        actions={[
          { key: 'cancel', text: '取消', onClick: () => { return; } },
          { key: 'ok', text: '确认转账', bold: true, onClick: () => { handleTransfer(); return; } },
        ]}
      />
    </div>
  );
}
